/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.accident.service.impl;

import com.google.gson.Gson;
import com.koron.accident.domain.AccidentReport;
import com.koron.accident.domain.PeccancyRecord;
import com.koron.accident.mapper.AccidentReportMapper;
import com.koron.accident.mapper.PeccancyRecordMapper;
import com.koron.accident.service.api.AccidentReportService;
import com.koron.accident.util.BusinessCode;
import com.koron.audit.approval.AfterApprovalService;
import com.koron.audit.domain.Audit;
import com.koron.audit.management.FlowManagement;
import com.koron.common.bean.StaffBean;
import com.koron.common.dfs.FastDFSClientWrapper;
import com.koron.common.domain.DataBean;
import com.koron.common.generator.DefaultIdGenerator;
import com.koron.common.util.DocConverterUtils;
import com.koron.hazardsource.util.Immutable;
import com.koron.system.domain.DictData;
import com.koron.system.service.api.DictDataService;
import org.apache.commons.lang3.StringUtils;
import org.koron.ebs.mybatis.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.swan.bean.MessageBean;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class AccidentReportServiceImpl implements AccidentReportService, AfterApprovalService, InitializingBean {
    private final Logger logger = LoggerFactory.getLogger(AccidentReportServiceImpl.class);

    @Autowired
    private FastDFSClientWrapper clientWrapper;

    @Autowired
    private DocConverterUtils docConverterUtils;

    @Autowired
    private FlowManagement flowManagement;

    @Autowired
    private DictDataService dataService;

    @Value("${accident_report}")
    private String accidentReport;
    @Override
    public MessageBean<Integer> save(StaffBean user, AccidentReport report, List<PeccancyRecord> peccancyRecords, String keepFiles, String delFiles,
                                     String keepPdfFiles, String delPdfFiles, MultipartFile[] files) {
        MessageBean<Integer> msg = new MessageBean<>();
        List<String> keepList = new ArrayList<>();
        List<String> keepPdfList = new ArrayList<>();
        SessionFactory factory = new SessionFactory();
        try {
            if (StringUtils.isEmpty(report.getAccidentBulletinId()) || StringUtils.isEmpty(report.getName())) {
                msg.setCode(BusinessCode.ACCIDENTREPORT_EMPTY_NAME.getCode());
                msg.setDescription(BusinessCode.ACCIDENTREPORT_EMPTY_NAME.getDescription());
                return msg;
            }
            if (StringUtils.isEmpty(report.getCorpCode())) {
                msg.setCode(BusinessCode.ACCIDENTREPORT_EMPTY_CORP.getCode());
                msg.setDescription(BusinessCode.ACCIDENTREPORT_EMPTY_CORP.getDescription());
                return msg;
            }
            if (StringUtils.isEmpty(report.getAccidentType())) {
                msg.setCode(BusinessCode.ACCIDENTREPORT_EMPTY_ACCIDENTTYPE.getCode());
                msg.setDescription(BusinessCode.ACCIDENTREPORT_EMPTY_ACCIDENTTYPE.getDescription());
                return msg;
            }
            if (StringUtils.isEmpty(report.getDepartmentCode()) || StringUtils.isEmpty(report.getDepartmentName())) {
                msg.setCode(BusinessCode.ACCIDENTREPORT_EMPTY_DEPARTMENTCODE.getCode());
                msg.setDescription(BusinessCode.ACCIDENTREPORT_EMPTY_DEPARTMENTCODE.getDescription());
                return msg;
            }
            if (StringUtils.isEmpty(report.getManager()) || StringUtils.isEmpty(report.getManagerName())) {
                msg.setCode(BusinessCode.ACCIDENTREPORT_EMPTY_MANAGER.getCode());
                msg.setDescription(BusinessCode.ACCIDENTREPORT_EMPTY_MANAGER.getDescription());
                return msg;
            }
            if (null != files && files.length > 0) {
                for (MultipartFile file : files) {
                    String url = clientWrapper.uploadFile(file);
                    keepList.add(url + "#" + file.getOriginalFilename());
                    String pdfUrl = docConverterUtils.converterUpdate(file);
                    keepPdfList.add(StringUtils.isEmpty(pdfUrl) ? null : pdfUrl);
                }
            }
            report.setStatus(0);
            report.setIsRemove(0);
            Integer value = 0;
            Audit audit = new Audit();
            audit.setTitle((StringUtils.isEmpty(report.getId()) ? "新增事故报告：" : "修改事故报告") + report.getName());
            if (StringUtils.isEmpty(report.getId())) {
                //新增
                report.setId(DefaultIdGenerator.getInstance().generateLongId());
                report.setAddTime(report.getUpdateTime());
                report.setAddUser(report.getUpdateUser());
                report.setAddUserName(report.getUpdateUserName());
                if (!keepList.isEmpty()) {
                    report.setAttachment(new Gson().toJson(keepList));
                    report.setPreviewAttachment(new Gson().toJson(keepPdfList));
                }
                //新增事故报告
                factory.getMapper(AccidentReportMapper.class).insert(report);
                if (!peccancyRecords.isEmpty()) {
                    for (PeccancyRecord record : peccancyRecords) {
                        record.setId(DefaultIdGenerator.getInstance().generateLongId());
                        record.setUpdateTime(report.getUpdateTime());
                        record.setUpdateUser(report.getUpdateUser());
                        record.setUpdateUserName(report.getUpdateUserName());
                        record.setAddTime(report.getUpdateTime());
                        record.setAddUser(report.getUpdateUser());
                        record.setAddUserName(report.getUpdateUserName());
                        record.setBusinessId(report.getId());
                        record.setPeccancyType(1);
                    }
                    factory.getMapper(PeccancyRecordMapper.class).batchInsert(peccancyRecords);
                }
            } else {
                //修改
                AccidentReport entity = queryOne(report.getId()).getData();
                if (null == entity) {
                    msg.setCode(BusinessCode.ACCIDENTREPORT_NOT_EXIST.getCode());
                    msg.setDescription(BusinessCode.ACCIDENTREPORT_NOT_EXIST.getDescription());
                    return msg;
                }
                if (entity.getStatus() == 0) {
                    msg.setCode(BusinessCode.ACCIDENTREPORT_IS_APPROVEING.getCode());
                    msg.setDescription(BusinessCode.ACCIDENTREPORT_IS_APPROVEING.getDescription());
                    return msg;
                }
                report.setStatus(0);
                if (StringUtils.isNotEmpty(keepFiles)) {
                    String[] keepArray = keepFiles.split("[,，]");
                    keepList.addAll(Arrays.asList(keepArray).stream().map(String::trim).collect(Collectors.toList()));
                }
                if (StringUtils.isNotEmpty(keepPdfFiles)) {
                    String[] keepPdfArray = keepPdfFiles.split("[,，]");
                    keepPdfList.addAll(Arrays.asList(keepPdfArray).stream().map(String::trim).collect(Collectors.toList()));
                }
                if (null != keepList && keepList.size() > 0)
                    report.setAttachment(new Gson().toJson(keepList));
                if (null != keepPdfList && keepPdfList.size() > 0)
                    report.setPreviewAttachment(new Gson().toJson(keepPdfList));
                value = factory.getMapper(AccidentReportMapper.class).update(report);
                if (value > 0) {
                    if (StringUtils.isNotEmpty(delFiles)) {
                        String[] delArray = delFiles.split("[,，]");
                        for (String url : delArray) {
                            clientWrapper.deleteFile(url.split("#")[0]);
                        }
                    }
                    if (StringUtils.isNotEmpty(delPdfFiles)) {
                        String[] delPdfArray = delPdfFiles.split("[,，]");
                        for (String url : delPdfArray) {
                            clientWrapper.deleteFile(url.split("#")[0]);
                        }
                    }
                }
                //  List<PeccancyRecord> recordList=report.getPeccancyRecords();
                if (peccancyRecords != null && peccancyRecords.size() > 0) {
                    List<PeccancyRecord> delList = factory.getMapper(PeccancyRecordMapper.class).queryByBusinessId(report.getId(), null, null);
                    if (null != delList && delList.size() > 0) {
                        List<String> idList = delList.stream().map(PeccancyRecord::getId).collect(Collectors.toList());
                        factory.getMapper(PeccancyRecordMapper.class).batchDelete(idList);
                    }
                    for (PeccancyRecord record : peccancyRecords) {
                        record.setId(DefaultIdGenerator.getInstance().generateLongId());
                        record.setUpdateTime(report.getUpdateTime());
                        record.setUpdateUser(report.getUpdateUser());
                        record.setUpdateUserName(report.getUpdateUserName());
                        record.setAddTime(report.getUpdateTime());
                        record.setAddUser(report.getUpdateUser());
                        record.setAddUserName(report.getUpdateUserName());
                        record.setBusinessId(report.getId());
                        record.setPeccancyType(1);
                    }
                    factory.getMapper(PeccancyRecordMapper.class).batchInsert(peccancyRecords);
                }
            }
            //启动流程
            Date date = new Date();
            audit.setAddUser(report.getUpdateUserName());
            audit.setAddTime(date);
            audit.setUpdateUser(report.getUpdateUserName());
            audit.setUpdateTime(date);
            audit.setFlowType(1);
            audit.setFlowName(Immutable.ACCIDENT_REPORT);
            audit.setOperation(1);
            audit.setTarget(AccidentReportServiceImpl.class.getName());
            audit.setCorpCode(report.getCorpCode());
            audit.setBusinessIds(report.getId());
            audit.setInitiatorCode(report.getUpdateUser());
            audit.setDescription(report.getName() + "");
            audit.setState(1);
            audit.setTemplateKey(accidentReport);
            audit.setSetCode("institution_manage");
            audit.setInitiatorAccount(user.getUserid());
            audit.setId(DefaultIdGenerator.getInstance().generateLongId());
            Map<String, Object> businessMap = new HashMap<>();
            businessMap.put("manager", report.getManager());
            if (!flowManagement.initFlow(user, audit, businessMap)) {
                factory.close(false);
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("提交失败，原因是无法启动流程");
                return msg;
            }
            factory.close();
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setDescription("事故报告保存成功");
            msg.setData(value);
            return msg;
        } catch (Exception e) {
            if (null != keepList && keepList.size() > 0) {
                if (StringUtils.isEmpty(keepFiles)) {
                    for (String url : keepList) {
                        clientWrapper.deleteFile(url.split("#")[0]);
                    }
                } else {
                    List<String> keeps = Arrays.asList(keepFiles.split("[,，]"));
                    for (String url : keepList) {
                        if (!keeps.contains(url)) {
                            clientWrapper.deleteFile(url.split("#")[0]);
                        }
                    }
                }
            }
            if (null != keepPdfList && keepPdfList.size() > 0) {
                if (StringUtils.isEmpty(keepPdfFiles)) {
                    for (String url : keepPdfList) {
                        clientWrapper.deleteFile(url.split("#")[0]);
                    }
                } else {
                    List<String> keeps = Arrays.asList(keepPdfFiles.split("[,，]"));
                    for (String url : keepList) {
                        if (!keeps.contains(url)) {
                            clientWrapper.deleteFile(url.split("#")[0]);
                        }
                    }
                }
            }
            if (null != factory)
                factory.close(false);
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        } finally {
            if (null != factory)
                factory.close();
        }
    }

    @Override
    public MessageBean<Integer> delete(StaffBean user, String id) {
        MessageBean<Integer> msg = new MessageBean<>();
        SessionFactory factory = null;
        try {
            factory = new SessionFactory();
            if (StringUtils.isEmpty(id)) {
                msg.setCode(BusinessCode.ACCIDENTREPORT_NOT_CHANGE_DATA.getCode());
                msg.setDescription(BusinessCode.ACCIDENTREPORT_NOT_CHANGE_DATA.getDescription());
                return msg;
            }
            AccidentReport entity = queryOne(id).getData();
            if (null == entity) {
                msg.setCode(BusinessCode.ACCIDENTREPORT_NOT_EXIST.getCode());
                msg.setDescription(BusinessCode.ACCIDENTREPORT_NOT_EXIST.getDescription());
                return msg;
            }
            if (entity.getStatus() == 0) {
                msg.setCode(BusinessCode.ACCIDENTREPORT_IS_APPROVEING.getCode());
                msg.setDescription(BusinessCode.ACCIDENTREPORT_IS_APPROVEING.getDescription());
                return msg;
            }
            Integer status = entity.getStatus();
            if (status == 2) {
                entity.setIsRemove(1);
            } else {
                entity.setStatus(0);
            }
            Integer value = factory.getMapper(AccidentReportMapper.class).update(entity);
            if (value > 0) {
                if (status != 0 && status != 2) {
                    //启动流程
                    Date date = new Date();
                    Audit audit = new Audit();
                    audit.setAddUser(entity.getUpdateUserName());
                    audit.setAddTime(date);
                    audit.setUpdateUser(entity.getUpdateUserName());
                    audit.setUpdateTime(date);
                    audit.setFlowType(1);
                    audit.setFlowName(Immutable.DEL_ACCIDENT_REPORT);
                    audit.setOperation(2);
                    audit.setTarget(AccidentReportServiceImpl.class.getName());
                    audit.setTitle("删除事故报告：" + entity.getName());
                    audit.setCorpCode(entity.getCorpCode());
                    audit.setBusinessIds(entity.getId());
                    audit.setInitiatorCode(entity.getUpdateUser());
                    audit.setDescription(entity.getName() + "");
                    audit.setState(1);
                    audit.setTemplateKey(accidentReport);
                    audit.setSetCode("institution_manage");
                    audit.setInitiatorAccount(user.getUserid());
                    audit.setId(DefaultIdGenerator.getInstance().generateLongId());
                    Map<String, Object> businessMap = new HashMap<>();
                    businessMap.put("manager", entity.getManager());
                    if (!flowManagement.initFlow(user, audit, businessMap)) {
                        factory.close(false);
                        msg.setCode(BusinessCode.FAILURE.getCode());
                        msg.setDescription("提交失败，原因是无法启动流程");
                        return msg;
                    }
                }
                factory.close();
                msg.setCode(BusinessCode.SUCCESS.getCode());
                msg.setDescription("事故报告删除成功");
                msg.setData(value);
                return msg;
            } else {
                factory.close(false);
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("事故报告删除失败");
                msg.setData(value);
                return msg;
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            if (null != factory)
                factory.close(false);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        } finally {
            if (null != factory)
                factory.close();
        }
    }

    @Override
    public MessageBean<AccidentReport> queryOne(String id) {
        MessageBean<AccidentReport> msg = new MessageBean<>();
        try (SessionFactory factory = new SessionFactory()) {
            if (StringUtils.isEmpty(id)) {
                msg.setCode(BusinessCode.ACCIDENTREPORT_NOT_CHANGE_DATA.getCode());
                msg.setDescription(BusinessCode.ACCIDENTREPORT_NOT_CHANGE_DATA.getDescription());
                return msg;
            }
            AccidentReport report = factory.getMapper(AccidentReportMapper.class).queryOne(id);
            setNames(report);
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setDescription("查询事故报告详情成功");
            msg.setData(report);
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    @Override
    public MessageBean<DataBean<AccidentReport>> list(String corpCode, String name, String departmentCode, String accidentType, Integer start, Integer rows) {
        MessageBean<DataBean<AccidentReport>> msg = new MessageBean<>();
        try (SessionFactory factory = new SessionFactory()) {
            List<AccidentReport> list = factory.getMapper(AccidentReportMapper.class).queryByCondition(corpCode, name, departmentCode,
                    accidentType, null, null, start, rows);
            Integer totalNumber = factory.getMapper(AccidentReportMapper.class).countByCondition(corpCode, name, departmentCode, accidentType, null, null);
            rows = rows == null ? totalNumber : (rows <= 0 ? 1 : rows);
            Integer totalPage = (totalNumber > rows) ? (totalNumber % rows == 0 ? totalNumber / rows : totalNumber / rows + 1) : 1;
            DataBean<AccidentReport> dataBean = new DataBean<>();
            list.forEach(item -> setNames(item));
            dataBean.setList(list);
            dataBean.setPageSize(rows);
            dataBean.setTotalPage(totalPage);
            dataBean.setTotalNumber(totalNumber);
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setDescription("获取事故报告列表成功");
            msg.setData(dataBean);
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    @Override
    public MessageBean<List<AccidentReport>> queryAll(String corpCode, String name) {
        MessageBean<List<AccidentReport>> msg = new MessageBean<>();
        try (SessionFactory factory = new SessionFactory()) {
            List<AccidentReport> list = factory.getMapper(AccidentReportMapper.class).queryByCondition(corpCode, name, null,
                    null, null, null, null, null);
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setDescription("获取事故报告列表成功");
            msg.setData(list);
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    @Override
    public List<AccidentReport> exportList(StaffBean user, String corpCode, String name, String departmentCode, String accidentType) {
        try (SessionFactory factory = new SessionFactory()) {
            List<AccidentReport> list = factory.getMapper(AccidentReportMapper.class).queryByCondition(corpCode, name, departmentCode,
                    accidentType, null, null, null, null);
            if (null != list && list.size() > 0) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
                Map<String, DictData> cacheMap = dataService.getCacheMap();
                list.forEach(bean -> {
                    if (StringUtils.isNotEmpty(bean.getAccidentType())) {
                        DictData element = cacheMap.get(bean.getAccidentType());
                        bean.setAccidentTypeName(element == null ? null : element.getDictLabel());
                    }
                    if (null !=bean.getOccurrenceTime()){
                        bean.setOccurrenceTimeStr(sdf.format(bean.getOccurrenceTime()));
                    }
                    if (null != bean.getCompleteTime()){
                        bean.setCompleteTimeStr(sdf1.format(bean.getCompleteTime()));
                    }
                });
            }
            return list;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            return null;
        }
    }

    private void setNames(AccidentReport bean) {
        if (bean != null) {
            Map<String, DictData> cacheMap = dataService.getCacheMap();
            if (StringUtils.isNotEmpty(bean.getAccidentType())) {
                DictData element = cacheMap.get(bean.getAccidentType());
                bean.setAccidentTypeName(element == null ? null : element.getDictLabel());
            }
        }
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        Map map = flowManagement.getHandlers();
        map.put(AccidentReportServiceImpl.class.getName(), this);
    }

    @Override
    public void editApproval(Audit audit) {
        SessionFactory factory = null;
        try {
            factory = new SessionFactory();
            AccidentReport report = factory.getMapper(AccidentReportMapper.class).queryOne(audit.getBusinessIds());
            if (null != report) {
                report.setStatus(1);
                factory.getMapper(AccidentReportMapper.class).update(report);
            }
            factory.close();
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            if (null != factory)
                factory.close(false);
        }
    }

    @Override
    public void discardApproval(Audit audit) {
        SessionFactory factory = null;
        try {
            factory = new SessionFactory();
            AccidentReport report = factory.getMapper(AccidentReportMapper.class).queryOne(audit.getBusinessIds());
            if (null != report) {
                report.setStatus(1);
                report.setIsRemove(1);
                factory.getMapper(AccidentReportMapper.class).update(report);
            }
            factory.close();
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            if (null != factory)
                factory.close(false);
        }
    }

    @Override
    public void processDiscard(Audit audit) {
        SessionFactory factory = null;
        try {
            factory = new SessionFactory();
            AccidentReport report = factory.getMapper(AccidentReportMapper.class).queryOne(audit.getBusinessIds());
            if (null != report) {
                if (Immutable.ACCIDENT_REPORT.equals(audit.getFlowName())) {
                    //保存事故报告
                    if (report.getAddTime().compareTo(report.getUpdateTime()) == 0) {
                        //新增流程被废弃
                        report.setStatus(2);
                    } else {
                        //修改流程被废弃
                        report.setStatus(3);
                    }
                }
                if (Immutable.DEL_ACCIDENT_REPORT.equals(audit.getFlowName())) {
                    //删除流程被废弃
                    report.setStatus(4);
                }
                factory.getMapper(AccidentReportMapper.class).update(report);
            }
            factory.close();
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            if (null != factory)
                factory.close(false);
        }
    }

    @Override
    public void reject(Audit audit, List<String> userIdList) {
        // TODO 流程驳回操作
    }

    @Override
    public void passApproval(Integer operation, Audit audit) {
        // TODO 流程提交成功操作
    }
}
